package campus.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ImageUtil {

    //1.定义变量保存生成后的验证码字符串
    static String code = "";

    //2.生成验证码
    public static String createcode() {
        code = "";
        String a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";//随机生成的字符范围(0-9,a-z,A-Z)

//生成验证码的位数(这里是4位)
        for (int i = 0; i < 4; i++) {
            int index = (int) (Math.random() * 62);//会产生一个[0,62)的数，不包含小数
            char b = a.charAt(index);
            code = code + b;
        }
        return code;
    }

    //查看已经生成的验证码
    public static String getCode() {
        return code;
    }

    //3.生成图片
    public static BufferedImage createimage() {
// 前2个参数为：width, height.后面是图像类型
//创建一个不带透明色的BufferedImage对象,TYPE_INT_ARGB为带透明色
        BufferedImage bi = new BufferedImage(130,50, BufferedImage.TYPE_INT_RGB);

//1.得到一个画布
        Graphics g = bi.getGraphics();
//2.添加背景颜色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 130, 50);

//3.添加干扰线
        for (int i = 0; i < 10; i++) {
            Random r = new Random();
            int red = r.nextInt(256);
            int green = r.nextInt(256);
            int blue = r.nextInt(256);
            Color c = new Color(red, green, blue);
            g.setColor(c);
            int x1 = r.nextInt(131);
            int y1 = r.nextInt(51);
            int x2 = r.nextInt(131);
            int y2 = r.nextInt(51);
            g.drawLine(x1,y1,x2,y2);//画线
//g.drawOval(x1, y1, x2, y2);//画曲线
        }


//3.添加文字
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体", Font.BOLD, 50));

        String str = getCode();
//4.将文字填充到画板中
        g.drawString(str, 15, 40);

//5.关闭画布
        g.dispose();
        return bi;
    }

}
